global repayoption  xti("Years") ///
	xlabel(365 "1" 730 "2" 1095 "3" 1460 "4") ///
	xline(730, lpattern(dash) lcolor(gs13)) ///
	xline(1095, lpattern(dash) lcolor(gs13)) ///
	leg(off)

**********************************************************************

use "${datadir}\HCA_full.dta", clear


merge 1:1 schemeid using "${datadir}\HCA_redemptions_all"
drop if _merge == 2	// only 10 obs



*--- Outcome variable
drop if Transactiontype == "Sale by repossession"
gen outcome = cond( regexm(Transactiontype, "staircasing"), 1, ///
	cond(Transactiontype == "Sale", 2, 0))


	
*--- Duration at risk

// create duration
gen duration = cond(mi(CompletionDate), 21090 - dated, CompletionDate - dated)



*--- Simple analysis by cohort
gen year = year(dated)
tab year

// Repayments
forvalues year = 2013 / 2016 {
	preserve
		keep if year == `year'
		count
		
		keep if outcome == 1
		sort duration
		keep duration
		gen cumrepay`year' = _n /  r(N)
		
		collapse (max) cumrepay`year', by(duration)
		
		tempfile cumrepay`year'
		save `cumrepay`year''
	restore
}
preserve
use `cumrepay2013', clear
forvalues year = 2014/2016 {
	merge 1:1 duration using `cumrepay`year'', gen(merge`year')
}
line cumrepay2013 cumrepay2014 cumrepay2015 cumrepay2016 ///
	duration, sort ${graphoption} ${repayoption} ///
	ti("Repayments w/o sale") name(gr1, replace) ///
	text(.105 1650 "2013") text(.09 1400 "2014") text(.04 1050 "2015") ///
	text(.003 650 "2016") graphregion(margin(large))
restore



// Sales
forvalues year = 2013 / 2016 {
	preserve
		keep if year == `year'
		count
		
		keep if outcome == 2
		sort duration
		keep duration
		gen outcome`year' = _n  /  r(N)
		
		collapse (max) outcome`year', by(duration)
		
		tempfile outcome`year'
		save `outcome`year''	
	restore
}
preserve
	use `outcome2013', clear
	forvalues year = 2014/2016 {
		capture merge 1:1 duration using `outcome`year'', gen(merge`year')
	}
	line outcome2013 outcome2014 outcome2015 outcome2016 ///
		duration, sort ${graphoption} ${repayoption} ///
		ti("Sales") name(gr2, replace)  ///
		text(.1575 1650 "2013") text(.095 1420 "2014") text(.03 1025 "2015") ///
		text(.005 675 "2016") graphregion(margin(large))
restore

gr combine gr1 gr2, graphregion(color(white)) xsize(8) ycommon	///
	scale(1.2) 
graph export "${figuredir}\cumulative_redemption.pdf", as(pdf) replace
